package com.jxtti.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jxtti.entity.Attach;
import com.jxtti.entity.SubjectAuth;
import com.jxtti.entity.SubjectMenu;
import com.jxtti.entity.SubjectTemplate;
import com.jxtti.entity.SubjectTopic;
import com.jxtti.model.User;
import com.jxtti.service.SubjectAuthService;
import com.jxtti.service.SubjectMenuService;
import com.jxtti.service.SubjectTemplateService;
import com.jxtti.service.SubjectTopicService;
import com.jxtti.utils.AuthUtil;
import com.jxtti.utils.CommConstant;
import com.jxtti.utils.ExceptionUtil;
import com.jxtti.utils.FileOperate;
/**
 * 
 * <br>
 * <b>功能：</b>SubjectTopicController<br>
 * <b>作者：lwb</b><br>
 * <b>日期：</b> Nov 26, 2015 <br>
 * <b>版权所有：<b>版权所有(C) 2015，<br>
 */ 
@Controller
@RequestMapping("/subjectTopic") 
public class SubjectTopicController {
	
	private final static Logger log= Logger.getLogger(SubjectTopicController.class);
	
	// Servrice start
	@Autowired
	private SubjectTopicService  subjectTopicService; 
	
	@Autowired
	private SubjectTemplateService  subjectTemplateService; 
	
	@Autowired
	private SubjectMenuService  subjectMenuService; 
	
	@Autowired
	private SubjectAuthService  subjectAuthService; 
	
	
	
	@RequestMapping(value="/testList") 
	public ModelAndView  testList(@RequestParam Map<String, Object> data,  SubjectTopic subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		ModelAndView mav = new ModelAndView();
		try {
			  /*	
			   * URL url = new URL("http://115.149.129.98:82/HBJ-Web/WebSubject/SubMenuPage.htm?id=60");     
		       
			  	URLConnection connection = url.openConnection();     
		        connection.addRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
		        connection.setDoOutput(true);     
		          
		        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");     
		        out.write("username=kevin&password=*********"); //向页面传递数据。post的关键所在！     
		        // remember to clean up     
		        out.flush();     
		        out.close();     
		       
		        // 一旦发送成功，用以下方法就可以得到服务器的回应：     
		        String sCurrentLine;     
		        String sTotalString;     
		        sCurrentLine = "";     
		        sTotalString = "";     
		        InputStream l_urlStream;     
		        l_urlStream = connection.getInputStream();     
		        // 传说中的三层包装阿！     
		        BufferedReader l_reader = new BufferedReader(new InputStreamReader(     
		                l_urlStream));     
		        while ((sCurrentLine = l_reader.readLine()) != null) {     
		            sTotalString += sCurrentLine ;     
		        }     
		        System.out.println(sTotalString);     
			*/
			
			mav.setViewName("/pages/Admin/subject/test.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return mav;
	}
	
	
	
	
	
	
	
	
	/**
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/list") 
	public ModelAndView  list(@RequestParam Map<String, Object> data,  SubjectTopic subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		ModelAndView mav = new ModelAndView();
		try {
			data =  subjectTopicService.list(data, subjectTopic);
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/subject/subject_topic_list.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return mav;
	}
	
	
	/**
	 * 
	 * @param data
	 * @param subjectTopic
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listData") 
	@ResponseBody
	public List<SubjectTopic>  listData(@RequestParam Map<String, Object> data,  SubjectTopic subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		return this.subjectTopicService.queryAll(data);
	}
	
	
	@RequestMapping(value="/listDataByAuth") 
	@ResponseBody
	public List<SubjectTopic>  listDataByAuth(@RequestParam Map<String, Object> data,  SubjectTopic subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		User user = AuthUtil.getUserInfo(request);
		data.put("org_id", user.getOrgId());
		return subjectTopicService.queryByAuth(data);
	}
	
	@RequestMapping(value="/querySubjectTopic") 
	@ResponseBody
	public List<SubjectTopic>  querySubjectTopic(@RequestParam Map<String, Object> data,  SubjectTopic subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{	
		List<SubjectTopic> lstSubjectTopic = subjectTopicService.queryPublishSubjectTopic(data);
		
		return lstSubjectTopic;
	}
	
	
	
	/**
	 * 点击添加跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addInterface")
	@ResponseBody
	public ModelAndView addInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/subject/subject_topic_add.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	
	@RequestMapping(value = "/getEasyUiTree")
	@ResponseBody
	public List<SubjectTopic> getEasyUiTree(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		
		List<SubjectTopic>  lst = new ArrayList();
		return lst;
	}
	
	
	
	
	
	
	@RequestMapping(value = "/topic_publish")
	@ResponseBody
	public Map<String,Object> topic_publish(@RequestParam Map<String, Object> data,
			SubjectTopic  subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		try {
				subjectTopic = this.subjectTopicService.querySubjectTopicById(subjectTopic);
				subjectTopic.setIs_publish(1);  //改新发布状态.
			
				int exeCount = subjectTopicService.update(subjectTopic);
				if (exeCount > 0) {
					data.put("success", true);
				} else {
					data.put("success", false);
				}
		} catch (Exception e) {
			e.getMessage();
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	
	@RequestMapping(value = "/topic_unPublish")
	@ResponseBody
	public Map<String,Object> topic_unPublish(@RequestParam Map<String, Object> data,
			SubjectTopic  subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		try {
				subjectTopic = this.subjectTopicService.querySubjectTopicById(subjectTopic);
				subjectTopic.setIs_publish(0);  //改新发布状态.
			
				int exeCount = subjectTopicService.update(subjectTopic);
				if (exeCount > 0) {
					data.put("success", true);
				} else {
					data.put("success", false);
				}
		} catch (Exception e) {
			e.getMessage();
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String,Object> save(@RequestParam Map<String, Object> data,
			SubjectTopic  subjectTopic, HttpServletRequest request,
			HttpServletResponse response) throws Exception{

		ModelAndView mav = new ModelAndView();
		try {
			// 保存数据
			List<Attach> lst = FileOperate.savefile(response, request, CommConstant.ATTACH_FILE);
			if(lst.size() > 0)
			{
				Attach attach = lst.get(0);
				subjectTopic.setTitle_image(attach.getAttach_path());
			}
			
			List<Attach> lst_bg = FileOperate.savefile(response, request,  CommConstant.ATTACH_FILE, "fileToUpload_bg");
			if(lst_bg.size() > 0)
			{
				Attach attach = lst_bg.get(0);
				subjectTopic.setTopic_bg_image(attach.getAttach_path());
			}
			
			List<Attach> sec_lst_bg = FileOperate.savefile(response, request,  CommConstant.ATTACH_FILE, "secFileToUpload_bg");
			if(sec_lst_bg.size() > 0)
			{
				Attach attach = sec_lst_bg.get(0);
				subjectTopic.setSec_topic_bg_image(attach.getAttach_path());
			}
			
			int exeCount = subjectTopicService.add(subjectTopic);
			//添加权限值 
			SubjectAuth  subjectAuth ;
			String tid = data.get("topic_auth").toString();
			String ids[] = tid.split(","); 
			for(int i  = 0; i< ids.length; i++)
			{
				subjectAuth = new SubjectAuth();
				subjectAuth.setCreate_time(new Date());
				subjectAuth.setTopic_id(subjectTopic.getId());
				subjectAuth.setOrg_id(ids[i]);
				subjectAuthService.add(subjectAuth);
			}
		
			
			initTopicMenu(subjectTopic);
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	/**
	 * 初始化菜单模版.
	 * @param templateId
	 * 
	 *  java.lang.String title,
	 java.lang.Integer parent_id,   
	 java.lang.String summary,   
	 java.lang.Integer seq,   
	 java.lang.String flag,  
	 java.lang.Integer is_publish,  
	 java.lang.Integer topic_id )
	 */
	public void initTopicMenu(SubjectTopic  subjectTopic )
	{
		SubjectTemplate st = new SubjectTemplate();
		st.setId(subjectTopic.getTemplate_id());
		st = this.subjectTemplateService.querySubjectTemplateById(st);
		List<SubjectMenu> lstSubjectMenu = new ArrayList();
		switch (st.getFalg())
		{
			case CommConstant.SUBJECT_STJS : //环境建设专题.
				//初始化一级栏目.
				lstSubjectMenu.add(new SubjectMenu("工作动态",0,"",1,"gzdt",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("工作简报",0,"",2,"gzjb",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("通知公告",0,"",3,"tzgg",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("政策解读",0,"",4,"zcjd",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("政策文件",0,"",5,"zcwj",1,subjectTopic.getId()));
				break;
			case CommConstant.SUBJECT_WRYJG:
				lstSubjectMenu.add(new SubjectMenu("环境应急",0,"",1,"fjyj",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("行政处罚",0,"",2,"xzcf",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("排污费征收",0,"",3,"pwhzs",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("监察执法",0,"",4,"jczf",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("污染防治",0,"",5,"wrfz",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("污染源监测",0,"",6,"wryjc",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("污染源基本信息",0,"",7,"wry_baseinfo",1,subjectTopic.getId()));
				break;
			case CommConstant.SUBJECT_RED:
				lstSubjectMenu.add(new SubjectMenu("活动运态",0,"",1,"hddt",1,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("工作动态",0,"",1,"gzdt",2,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("相关文件",0,"",1,"xgwj",3,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("上级精神",0,"",1,"sjjs",4,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("心得体会",0,"",1,"bdth",5,subjectTopic.getId()));
				lstSubjectMenu.add(new SubjectMenu("一张图解读",0,"",1,"yzt",6,subjectTopic.getId()));
				break;
		}
		
		for(SubjectMenu sm : lstSubjectMenu)
		{
			this.subjectMenuService.add(sm);
		}
	}
	
	
	
	/**
	 * 点击修改跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateInterface")
	@ResponseBody
	public ModelAndView updateInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, SubjectTopic  subjectTopic,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			subjectTopic = subjectTopicService.querySubjectTopicById(subjectTopic);
			data.put("subjectTopic", subjectTopic);
			
			//获取授权信息
			Map<String, Object> d = new HashMap();
			d.put("topic_id", subjectTopic.getId());
			List<SubjectAuth>  lstAuth = this.subjectAuthService.queryAll(d);
			StringBuffer value = new StringBuffer();
			StringBuffer key = new StringBuffer();
			
			for(int i =0; i<lstAuth.size(); i++ )
			{
				SubjectAuth sAuth  = lstAuth.get(i);
				value.append(sAuth.getOrg_id()).append(",");
				key.append(sAuth.getAuth_name()).append(",");
			}
			String tvalue = value.toString().contains(",") ? value.toString().substring(0, value.toString().lastIndexOf(",")): value.toString();
			String kvalue = key.toString().contains(",") ? key.toString().substring(0, key.toString().lastIndexOf(",")): key.toString();
			data.put("authValue", tvalue);
			data.put("authKey", kvalue);
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/subject/subject_topic_edit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	
	
	
	
	
	
	/**
	 * 修改信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update(@RequestParam Map<String, Object> data,
			SubjectTopic  subjectTopic, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 修改
			SubjectTopic subjectTopicTem=subjectTopicService.querySubjectTopicById(subjectTopic);
			List<Attach> lst = FileOperate.savefile(response, request, CommConstant.ATTACH_FILE);
			if(lst.size() > 0)
			{
				Attach attach = lst.get(0);
				subjectTopic.setTitle_image(attach.getAttach_path());
			}else
			{
				subjectTopic.setTitle_image(subjectTopicTem.getTitle_image());
			}
			//修改背景图
			List<Attach> lst_bg = FileOperate.savefile(response, request,  CommConstant.ATTACH_FILE, "fileToUpload_bg");
			if(lst_bg.size() > 0)
			{
				Attach attach = lst_bg.get(0);
				subjectTopic.setTopic_bg_image(attach.getAttach_path());
			}else
			{
				subjectTopic.setTopic_bg_image(subjectTopicTem.getTopic_bg_image());
			}
			
			
			
			List<Attach> sec_lst_bg = FileOperate.savefile(response, request,  CommConstant.ATTACH_FILE, "secFileToUpload_bg");
			if(sec_lst_bg.size() > 0)
			{
				Attach attach = sec_lst_bg.get(0);
				subjectTopic.setSec_topic_bg_image(attach.getAttach_path());
			}else
			{
				subjectTopic.setSec_topic_bg_image(subjectTopicTem.getSec_topic_bg_image());
			}
			
			//修改授权
			int exeCount = subjectTopicService.update( subjectTopic);
			//删除原有权限值
			SubjectAuth  subjectAuth =new SubjectAuth();
			subjectAuth.setTopic_id(subjectTopic.getId());
			subjectAuthService.deleteAuth(subjectAuth);
			//添加权限值 
			String tid = data.get("topic_auth").toString();
			String ids[] = tid.split(","); 
			for(int i  = 0; i< ids.length; i++)
			{
				subjectAuth = new SubjectAuth();
				subjectAuth.setCreate_time(new Date());
				subjectAuth.setTopic_id(subjectTopic.getId());
				subjectAuth.setOrg_id(ids[i]);
				subjectAuthService.add(subjectAuth);
			}

			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	

/**
	 * 删除信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam Map<String, Object> data,
			SubjectTopic  subjectTopic, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			subjectTopic=subjectTopicService.querySubjectTopicById( subjectTopic);
			int exeCount = subjectTopicService.delete(subjectTopic);
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}








	
	
	
}
